package cn.hg.solon.youcan.framework.web.qo;

import cn.hg.solon.youcan.common.vo.IPaginationObject;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.Page;
import org.dromara.hutool.db.sql.Direction;
import org.dromara.hutool.db.sql.Order;
import org.dromara.hutool.json.JSONUtil;

import java.util.Iterator;
import java.util.Map;

public class PaginationQueryObject extends Page implements IPaginationObject {

    private String sortField;

    private String sortType;

    private String word;

    public String getWord() {
        return this.word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public String getSortField() {
        return this.sortField;
    }

    public String getSortType() {
        return this.sortType;
    }

    public void setSortField(String sortField) {
        this.sortField = sortField;
    }

    public void setSortType(String sortType) {
        this.sortType = sortType;
    }

    @Override
    public Order[] getOrders() {
        Order[] orderArray = super.getOrders();
        if (StrUtil.isNotBlank(this.sortField)) {
            Direction d = Direction.ASC;
            if (StrUtil.isNotBlank(this.sortType)) {
                d = Direction.fromString(this.sortType);
            }
            Order theSort = new Order(this.sortField, d);

            if (ArrayUtil.isEmpty(orderArray)) {
                orderArray = ArrayUtil.append(new Order[]{}, theSort);
            } else if (!ArrayUtil.contains(orderArray, theSort)) {
                ArrayUtil.append(orderArray, theSort);
            }
        }
        return orderArray;
    }

    public Map<String, Object> toMap() {
        return BeanUtil.beanToMap(this, false, true);
    }

    @Override
    public String toString() {
        Map<String, Object> map = this.toMap();

        Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            if (StrUtil.isBlankIfStr(entry.getValue()) || ObjUtil.isNull(entry.getValue())
                || StrUtil.equals(entry.getKey(), "sortField") || StrUtil.equals(entry.getKey(), "sortType")) {
                iterator.remove();
            }
        }
        return JSONUtil.toJsonStr(map);
    }
}
